package com.pattern.parallel.future;

import java.util.concurrent.*;

/**
 * 通过Future实现
    与上述FutureTask不同的是, RealData需要实现Callable接口.
 */
public class FutureDemo2 {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newCachedThreadPool();
        Future<String> future = service.submit(new RealData2());

        System.out.println("RealData2方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData2方法的结果
        System.out.println(future.get());

        //另外Future本身还提供了一些额外的简单控制功能, 其API如下
        /*// 取消任务
        boolean cancel(boolean mayInterruptIfRunning);
        // 是否已经取消
        boolean isCancelled();
        // 是否已经完成
        boolean isDone();
        // 取得返回对象
        V get() throws InterruptedException, ExecutionException;
        // 取得返回对象, 并可以设置超时时间
        V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;*/
    }

    private static void doOtherThing() throws InterruptedException {
        Thread.sleep(2000L);
    }
}

class RealData2 implements Callable<String> {

    public String costTime() {
        try {
            // 模拟RealData耗时操作
            Thread.sleep(1000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }

    @Override
    public String call() throws Exception {
        return costTime();
    }
}